package november.tree.arraytree;

/**
 * @author huangxin
 * @date 2019/11/21-10:22
 */
public class ArrayBinaryTree {
    public static void main(String[] args) {
        int[] arr = {1, 3, 6, 8, 10, 14};
        ArrayBinaryTree binaryTree = new ArrayBinaryTree(arr);
        binaryTree.infixOrder();
    }

    private int[] arr;

    public ArrayBinaryTree(int[] arr) {
        this.arr = arr;
    }


    public void preOrder(){
        preOrder(0);
    }
    //数组存储前序遍历
    public void preOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空");
        }

        System.out.println(arr[index]);

        //向左递归
        int left = 2 * index + 1;
        if (left < arr.length) {
            preOrder(left);
        }

        //向右递归
        int right = 2 * index + 2;
        if (right < arr.length) {
            preOrder(right);
        }
    }

    public void infixOrder(){
        infixOrder(0);
    }
    //数组存储中序遍历
    public void infixOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空");
        }


        //向左递归
        int left = 2 * index + 1;
        if (left < arr.length) {
            infixOrder(left);
        }

        //中间输出当前节点
        System.out.println(arr[index]);

        //向右递归
        int right = 2 * index + 2;
        if (right < arr.length) {
            infixOrder(right);
        }
    }


    public void afterOrder(){
        afterOrder(0);
    }
    //数组存储后序遍历
    public void afterOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空");
        }


        //向左递归
        int left = 2 * index + 1;
        if (left < arr.length) {
            afterOrder(left);
        }


        //向右递归
        int right = 2 * index + 2;
        if (right < arr.length) {
            afterOrder(right);
        }

        //最后输出自身
        System.out.println(arr[index]);

    }
}
